package com.caowei.weicimpress.weicimpress;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.caowei.weicimpress.weicimpress.widget.AlertDialog;
import com.caowei.weicimpress.weicimpress.widget.Toast;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;


/**
 * Created by caoweiPc on 2014/7/15.
 */
public class CompressFileFragment extends ActionBarBaseFragment {
    public final static String INPUTPASSWD_ACTION=CompressFileFragment.class.getName()+".action.VIEW";
    private static final String TAG=CompressFileFragment.class.getSimpleName();
    private static final int REQUESTCODE_PASSWD_0=0;
    private static final int REQUESTCODE_PASSWD_1=1;
    private List<FileInfoBean> extractingBeans=new ArrayList<FileInfoBean>();
    @Override
    protected void init() {
        //todo test code  to do delete
//      rootFile=new File(Environment.getExternalStorageDirectory(),"Demo/gggg.zip");
        actionItemWithFileInfoBean=new ActionItemWithFileInfoBean();
        footer2_4.setText(getActivity().getString(R.string.extract));
        footer2_1.setVisibility(View.GONE);
    }
    @Override
    protected String[] getItemLongClickMenu(FileInfoBean bean) {
        String menu[]=null;
        menu=getActivity().getResources().
                getStringArray(R.array.compressfragment_longitemclick);
        return menu;
    }

    @Override
    protected void exeDialogOper(int position, final FileInfoBean bean) {
         switch (position){
             case 0:
                 String[] arr=null;
                 String[][] content=null;
                 String title=null;
                 long rootFileLastModifyTime=bean.getRootFile().lastModified();
                 long itemLastModifyTime=bean.getLastModFileTime();
                 itemLastModifyTime=itemLastModifyTime<=rootFileLastModifyTime?
                         rootFileLastModifyTime:itemLastModifyTime;

                 if(bean.isDir()){
                     arr= getActivity().getResources().getStringArray(R.array.compressdirproperty);
                     title=getActivity().
                             getResources().getString(R.string.dirpropertyname);
                     content=new String[][]{
                            new String[]{bean.getFileName()},
                             new String[]{bean.getParentPath()},
                            new String[]{Utils.formateDate(itemLastModifyTime,Utils.DEFAULTDATEPATTERNWITHA)},
                            new String[]{String.valueOf(bean.getNumOfSubFile())},
                            new String[]{Utils.normalSizeStr(
                                    BigDecimal.valueOf(bean.getRootFile().length()))}
                     };
                 }else{
                     arr= getActivity().getResources().getStringArray(R.array.compressfileproperty);
                     title=getActivity().
                             getResources().getString(R.string.filepropertyname);
                     content=new String[][]{
                             new String[]{bean.getFileName()},
                             new String[]{bean.getParentPath()},
                             new String[]{Utils.formateDate(itemLastModifyTime,Utils.DEFAULTDATEPATTERNWITHA)},
                             new String[]{Utils.normalSizeStr(bean.getSize())},
                             new String[]{Utils.normalSizeStr(
                                     BigDecimal.valueOf(bean.getRootFile().length()))}
                     };
                 }

                 List<GenerateDialog.ActionItem> list=new ArrayList<GenerateDialog.ActionItem>();
                 for(int i=0;i<arr.length;i++){
                     String str=arr[i];
                     GenerateDialog.ActionItem item=new GenerateDialog.ActionItem();
                     String str1=String.format(str,(Object[])content[i]);
                     item.setName(str1);
                     list.add(item);
                 }
                 AlertDialog dialog1= GenerateDialog.createSelectOperDialog(title,
                         getActivity(),list);
                 dialog1.show();
                 break;
             case 1:
                 extractingBeans.clear();
                 extractingBeans.add(bean);
                 //todo
                 inputPasswd();
                 break;
             case 2:
                 View.OnClickListener yesListener=new View.OnClickListener() {
                     @Override
                     public void onClick(View v) {
                         ArrayList<FileInfoBean> beans=new ArrayList<FileInfoBean>();
                         beans.add(bean);
                         beforeDelBeans(beans);
                     }
                 };
                AlertDialog dialog= GenerateDialog.createVerifyDialog(getActivity(),
                     getActivity().getResources().getString(R.string.confiremdel),
                         yesListener, null);
                 dialog.show();
                 break;
         }
    }

    private void deleteChildBeans(final List<FileInfoBean> beans, final char[] passwd){
        if(beans.size()>0){
            final FileInfoBean firstBean=beans.get(0);
            AsyncTask<Object,Object,Boolean> task=
                    new AsyncTask<Object,Object,Boolean>(){
                        private String delMsg="";
                        @Override
                        protected Boolean doInBackground(Object... params) {
                            boolean b=false;
                            try{
                                b=firstBean.getCompressFileHandler().delete(beans,passwd);
                            }catch (MyException e){
                                if(e.getCode()==MyException.FAIL_EXTRACT_BYPASSWDERROR){
                                    b=false;
                                    delMsg="密码出错!";
                                }
                            }
                            return b;
                        }
                        @Override
                        protected void onPostExecute(Boolean aBoolean) {
                            if(aBoolean){
                                Toast.makeText(getActivity(),
                                        getActivity().getResources().getString(R.string.success_del),
                                        Toast.LENGTH_SHORT).show();
                            }else{
                                Toast.makeText(getActivity(),
                                        getActivity().getResources().getString(R.string.fail_del,delMsg),
                                        Toast.LENGTH_SHORT).show();
                            }
                            showCoverProgress(false,null);
                            refresh();
                            if(footer2.getVisibility()==View.VISIBLE){
                                footer2.setVisibility(View.GONE);
                            }
                            enablefooterBtnes();
                            if (MyApplication.getAsyncTasks().contains(this)){
                                MyApplication.getAsyncTasks().remove(this);
                            }
                        }
                    };
            StringBuilder tip=new StringBuilder();
            if(beans.size()>1){
                tip.append(getActivity().getResources().getString(R.string.delfiles,firstBean.getFileName()));
            }else{
                tip.append(getActivity().getResources().getString(R.string.delfile,firstBean.getFileName()));
            }
            showCoverProgress(true,tip.toString());
            if(Build.VERSION.SDK_INT<Build.VERSION_CODES.HONEYCOMB){
                task.execute();
            }else{
                task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
            }
            if (!MyApplication.getAsyncTasks().contains(task)){
                MyApplication.getAsyncTasks().add(task);
            }
        }

    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode== Activity.RESULT_OK){
            List<FileInfoBean> rootFileBeans= data.getParcelableArrayListExtra("beans");
            switch (requestCode){
                case REQUESTCODE_PASSWD_0:
                    List<FileInfoBean> childrenBeans=data.getParcelableArrayListExtra("childrenBeans");
                    deleteChildBeans(childrenBeans, rootFileBeans.get(0).getPasswd());
                    break;
                case REQUESTCODE_PASSWD_1:
                    for (FileInfoBean bean:extractingBeans){
                        bean.setPasswd(rootFileBeans.get(0).getPasswd());
                    }
                    gotoSysFileFragment();
                    break;
            }
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()){
            case R.id.footer2_2:
                v.setEnabled(false);
                final List<FileInfoBean> selectedBeans= getSelectedItems();
                View.OnClickListener yesListener=new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                         beforeDelBeans((ArrayList<FileInfoBean>) selectedBeans);
                    }
                };
                String dialogTitle=getActivity().getResources().getString(R.string.delfiles);
                dialogTitle=String.format(dialogTitle,selectedBeans.get(0).getFileName());
                AlertDialog dialog= GenerateDialog.createVerifyDialog(getActivity(),
                        dialogTitle,
                        yesListener,new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                footer2_2.setEnabled(true);
                            }
                        });
                dialog.show();
                break;
            case R.id.footer2_4:
                v.setEnabled(false);
                extractingBeans.clear();
                extractingBeans.addAll(getSelectedItems());
                inputPasswd();
                break;
        }
    }

    public void beforeDelBeans(final ArrayList<FileInfoBean> beans){
        showCoverProgress(true,getActivity().getText(R.string.checking).toString());
        AsyncTask<Object,Object,ArrayList<FileInfoBean>> task=new AsyncTask<Object, Object,
                ArrayList<FileInfoBean>>() {
            @Override
            protected ArrayList<FileInfoBean> doInBackground(Object... params) {
                boolean splited=  beans.get(0).getCompressFileHandler().isSplite(rootFile);
                if(splited){
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getActivity(),getActivity().getText(R.string.spiltfilenotupdate),
                                    Toast.LENGTH_SHORT).show();
                        }
                    });
                    return null;
                }
                final FileHandler fileHandler= beans.get(0).getCompressFileHandler();
                boolean isCrypto=fileHandler.isEncried(rootFile);
                if(isCrypto){
                    Intent intent=new Intent(getActivity(),InputPasswdActivity.class);
                    intent.setAction(INPUTPASSWD_ACTION);
                    FileInfoBean rootBean=new FileInfoBean();
                    rootBean.setDir(false);
                    rootBean.setCompressed(true);
                    rootBean.setParentPath(Utils.normalizePath(rootFile.getParent()));
                    rootBean.setFileName(rootFile.getName());
                    ArrayList<FileInfoBean> rootBeans=new ArrayList<FileInfoBean>();
                    rootBeans.add(rootBean);
                    intent.putParcelableArrayListExtra("beans", rootBeans);
                    intent.putParcelableArrayListExtra("childrenBeans", beans);
                    startActivityForResult(intent, REQUESTCODE_PASSWD_0);

                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            footer2_2.setEnabled(true);
                        }
                    });
                    return null;
                }
                return beans;
            }

            @Override
            protected void onPostExecute(ArrayList<FileInfoBean> beans) {
                showCoverProgress(false,null);
                if(beans!=null){
                    deleteChildBeans(beans,null);
                }
                if(MyApplication.getAsyncTasks().contains(this)){
                    MyApplication.getAsyncTasks().remove(this);
                }
            }
        };
        if(Build.VERSION.SDK_INT<Build.VERSION_CODES.HONEYCOMB){
            task.execute();
        }else{
            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }
        if(!MyApplication.getAsyncTasks().contains(task)){
            MyApplication.getAsyncTasks().add(task);
        }

      /*  boolean splited=  beans.get(0).getCompressFileHandler().isSplite(rootFile);
        if(splited){
            Toast.makeText(getActivity(),"分割文件不允许更新!",
                    Toast.LENGTH_SHORT).show();
            return null;
        }
        final FileHandler fileHandler= beans.get(0).getCompressFileHandler();
        boolean isCrypto=fileHandler.isEncried(rootFile);
        if(isCrypto){
            Intent intent=new Intent(getActivity(),InputPasswdActivity.class);
            intent.setAction(INPUTPASSWD_ACTION);
            FileInfoBean rootBean=new FileInfoBean();
            rootBean.setDir(false);
            rootBean.setCompressed(true);
            rootBean.setParentPath(Utils.normalizePath(rootFile.getParent()));
            rootBean.setFileName(rootFile.getName());
            ArrayList<FileInfoBean> rootBeans=new ArrayList<FileInfoBean>();
            rootBeans.add(rootBean);
            intent.putParcelableArrayListExtra("beans", rootBeans);
            intent.putParcelableArrayListExtra("childrenBeans", beans);
            startActivityForResult(intent, REQUESTCODE_PASSWD_0);
            return null;
        }*/
    }

    private void gotoSysFileFragment(){
        Activity activity=getActivity();
        if(activity instanceof OnSwitchFragment){
            OnSwitchFragment switchFragment= (OnSwitchFragment) activity;
                 /*    Bundle bundle=new Bundle();
                     ArrayList<FileInfoBean> beans=new ArrayList<FileInfoBean>();
                     beans.add(bean);
                     bundle.putParcelableArrayList("beans",beans);*/
            showCoverLayout(true);
            enablefooterBtnes();
            switchFragment.switchFragment(SysFileFragment.class, new BaseFragment.Callback() {
                @Override
                public void onCallback(Callback1 callback) {
                    callback.onCallback(CompressFileFragment.class);
                }
            });
        }
    }

    private void inputPasswd(){
        final File rootFile=getRootFile();
        showCoverProgress(true,getActivity().getText(R.string.checking).toString());
        AsyncTask<Object,Object,Boolean> task=
                new AsyncTask<Object,Object,Boolean>() {
            @Override
            protected Boolean doInBackground(Object[] params) {
                //todo
                if(ExecuteFileHandler.getInstance().isEncried(rootFile)){
                    FileInfoBean rootBean=new FileInfoBean();
                    rootBean.setDir(false);
                    rootBean.setFileName(rootFile.getName());
                    rootBean.setParentPath(rootFile.getParent());

                    Intent i=new Intent(getActivity(),InputPasswdActivity.class);
                    ArrayList<FileInfoBean> beans=new ArrayList<FileInfoBean>();
                    beans.add(rootBean);
                    i.putParcelableArrayListExtra("beans",beans);
                    i.setAction(INPUTPASSWD_ACTION);
                    startActivityForResult(i,REQUESTCODE_PASSWD_1);
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            footer2_4.setEnabled(true);
                        }
                    });

                }else{
                    return false;
                }
                return true;
            }

            @Override
            protected void onPostExecute(Boolean aBoolean) {
               showCoverProgress(false,null);
               if(!aBoolean){
                   gotoSysFileFragment();
               }
                if(MyApplication.getAsyncTasks().contains(this)){
                    MyApplication.getAsyncTasks().remove(this);
                }
            }
        };
        //todo
        if(Build.VERSION.SDK_INT<Build.VERSION_CODES.HONEYCOMB){
            task.execute();
        }else{
            task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }
        if(!MyApplication.getAsyncTasks().contains(task)){
            MyApplication.getAsyncTasks().add(task);
        }
    }

    @Override
    protected void onSubItemClick(AdapterView<?> parent, View view, int position, long id) {
        FileInfoAdapter.ViewHolder viewHolder= (FileInfoAdapter.ViewHolder) view.getTag();
        Log.d(TAG, "onSubItemClick");
        FileInfoBean bean= viewHolder.getBean();
        if(!bean.isDir()){
            Toast.makeText(getActivity(), getActivity().getResources().getString(
                    R.string.notopen), Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onSubLongItemClick(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    protected LinearLayout findPathlayoutOnAtionbarLayout() {
        LinearLayout pathlayout= (LinearLayout) actionbarLayout.findViewById(R.id.pathlayout2);
        return pathlayout;
    }

    @Override
    protected TextView findPathPathOnAtionbarLayout() {
        TextView textView= (TextView) actionbarLayout.findViewById(R.id.path2);
        return textView;
    }

    public void extractBeans(final String saveDir, final Callback callback){
        if(extractingBeans.size()>0){
            final FileHandler fileHandler=extractingBeans.get(0).getCompressFileHandler();
            final String saveName=Utils.dropDotSuffix(extractingBeans.get(0).getRootFile().getName());
            StringBuilder sb=new StringBuilder(saveDir);
            sb.append(File.separator).append(saveName);

            final StringBuilder taskNameSb=new StringBuilder( getActivity().getResources().
                    getString(R.string.extract1, extractingBeans.get(0).getFileName()));
            final File targetDir=new File(Utils.normalizePath(sb.toString()));
            final View.OnClickListener yesListener=new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MyAsyncTask<Object,Object,File> myAsyncTask=new MyAsyncTask<Object, Object, File>() {
                        private String msg="";
                        @Override
                        protected File doInBackground(Object... params) {
                            String targetDir1Str= (String) params[0];
                            targetDir1Str=Utils.normalizePath(targetDir1Str);
                            File targetDir1=new File(targetDir1Str);
                            try{
                                if(targetDir1.exists()){
                                    Utils.del(targetDir1.getAbsolutePath());
                                }
                                for(FileInfoBean bean:extractingBeans){
                                    fileHandler.extractItem(targetDir1,bean);
                                }
                            }catch (MyException e){
                                if(targetDir1.exists()){
                                    Utils.del(targetDir1.getAbsolutePath());
                                }
                                if(e.getCode()==MyException.FAIL_EXTRACT_BYPASSWDERROR){
                                    msg="解压出错密码错误!";
                                }
                                return null;
                            }
                            return targetDir1;
                        }
                        @Override
                        protected void onPostExecute(File f) {
                            if(f==null){
                                Toast.makeText(getActivity(),msg,Toast.LENGTH_SHORT).show();
                                callback.callback(false, null);
                                return;
                            }
                            footer2_3.performClick();
                            callback.callback(true,f.getName());
                            enablefooterBtnes();
                        }

                        @Override
                        protected boolean onCancelled(File file) {
                            boolean b= Utils.del(file.getAbsolutePath());
                            if(b){
                                Intent i=new Intent(Utils.NOTIFYFILESYSTEMCHANGEINCURRENTDIR_ACTION);
                                i.putExtra("currentPath",file.getParent());
                                getActivity().sendBroadcast(i);
                            }
                            enablefooterBtnes();
                            return b;
                        }
                    };
                    StringBuilder sb1=new StringBuilder(saveDir);

                    if(v!=null&&v.getTag()!=null){
                        String saveName1= (String) v.getTag();
                        sb1.append(File.separator).append(saveName1);
                    }else{
                        sb1.append(File.separator).append(saveName);
                    }
                    Toast.makeText(getActivity(),taskNameSb.toString(),Toast.LENGTH_SHORT).show();
                    String tip=getActivity().getResources().getString(R.string.starttasktip,
                            taskNameSb.toString());
                    myAsyncTask.execute((MyApplication) getActivity().getApplication(),
                            tip,sb1.toString());
                }
            };
            if(targetDir.exists()&&targetDir.isDirectory()){
                StringBuilder sb1=new StringBuilder("覆盖目录:");
                sb1.append(saveName).append("?");

                GenerateDialog.BtnBean btnOk=new GenerateDialog.BtnBean();
                btnOk.setBtnText(getActivity().getResources().getString(R.string.ok));
                btnOk.setListener(yesListener);

                GenerateDialog.BtnBean btnModify=new GenerateDialog.BtnBean();
                btnModify.setBtnText(getString(R.string.modify));

                GenerateDialog.BtnBean btnCancle=new GenerateDialog.BtnBean();
                btnCancle.setBtnText(getString(R.string.cancle));

                final AlertDialog dialog= GenerateDialog.createVerifyDialog( getActivity(),sb1.toString(),
                        new GenerateDialog.BtnBean[]{btnOk,btnModify,btnCancle});
                btnModify.setListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        GenerateDialog.OnClickListener yeslistener=new GenerateDialog.OnClickListener() {
                            @Override
                            public void onClick(View v,GenerateDialog.CallbackDismiss callbackDismiss) {
                                StringBuilder sb=new StringBuilder(saveDir);
                                sb.append(File.separator);
                                sb.append(v.getTag());
                                File file=new File(Utils.normalizePath(sb.toString()));
                                if(file.exists()){
                                    callbackDismiss.onDismiss(false);
                                    return;
                                }else{
                                    callbackDismiss.onDismiss(true);
                                }
                                yesListener.onClick(v);
                            }
                        };
                        GenerateDialog.OnClickListener nolistener=new GenerateDialog.OnClickListener() {
                            @Override
                            public void onClick(View v,GenerateDialog.CallbackDismiss callbackDismiss) {
                                dialog.show();
                                callbackDismiss.onDismiss(true);
                            }
                        };
                        AlertDialog dialog1= GenerateDialog.createInputDialog("填写目录名:",
                                getActivity(),yeslistener,nolistener);
                        dialog1.show();
                    }
                });
                dialog.show();
            }else{
                yesListener.onClick(null);
            }
            cover_layout.setVisibility(View.GONE);
        }
    }

    public void extractEle(FileInfoBean bean){
        extractingBeans.clear();
        extractingBeans.add(bean);
        inputPasswd();
    }

    public void showCoverLayout(boolean b){
        int hide=b?View.VISIBLE:View.GONE;
        cover_layout.setVisibility(hide);
    }

    public interface  Callback{
        public   void callback(boolean isSuccess,String saveDirName);
    }
}
